import 'package:flutter/material.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:provider/provider.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/model/index_data_model.dart';
import 'package:yw_bapp/model/store_detail_model.dart';
import 'package:yw_bapp/model/store_list_model.dart';
import 'package:yw_bapp/pages/my_store.dart';
import 'package:yw_bapp/provider/manager_info_provider.dart';
import 'package:yw_bapp/provider/merchant_info_provider.dart';
import 'package:yw_bapp/provider/role_info_provider.dart';
import 'package:yw_bapp/provider/store_info_provider.dart';
import 'package:yw_bapp/provider/store_list_provider.dart';
import 'package:yw_bapp/utils/loacl_storage.dart';
import 'package:yw_bapp/utils/show_tip_pop.dart';
import 'package:yw_bapp/widgets/circle_check_box.dart';
import 'package:yw_bapp/widgets/custom_route_widget.dart';
import 'package:yw_bapp/widgets/loading_pop_widget.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';

import 'merchant_info.dart';

class StoreSelect extends StatefulWidget {
  @override
  _StoreSelectState createState() => _StoreSelectState();
}

class _StoreSelectState extends State<StoreSelect> {
  List<Store> storeList;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    storeList = List();
    // 数据请求
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: XAppBar(
        statusBarColor: ColorUtil.color('#FFC49226'),
        bgColor: ColorUtil.color('#FFC49226'),
        title: "门店选择",
        iconColor: Colors.white,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Expanded(
            flex: 1,
            child: Padding(
              padding: EdgeInsets.fromLTRB(15, 0, 15, 0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  // 标题
                  Text(
                    "请选择门店",
                    style: TextStyle(
                        color: ColorUtil.color("#FF999999"), fontSize: 13),
                  ),
                  // 门店列表
                  Expanded(
                      flex: 1,
                      child: ListView.builder(
                          itemCount: storeList.length,
                          itemBuilder: (BuildContext context, int index) {
                            return StoreItem(context, index);
                          }))
                ],
              ),
            ),
          ),
          Row(
            children: <Widget>[
              //按钮
              Expanded(
                  flex: 1,
                  child: MBtn(
                    hasBg: true,
                    btnHeight: 50,
                    bgColor: ColorUtil.color("#FFC49226"),
                    function: () {
                      _confirmStore(context);
                    },
                    borderColor: ColorUtil.color("#FFC49226"),
                    title: "确定",
                    borderRadius: 0,
                  ))
            ],
          )
        ],
      ),
    );
  }

  // 门店列表项
  Widget StoreItem(context, int index) {
    return Container(
      height: 72,
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.fromLTRB(12, 16, 12, 16),
      decoration: BoxDecoration(color: Colors.white, boxShadow: [
        BoxShadow(
            color: ColorUtil.color("#1A000000"), blurRadius: 8, spreadRadius: 1)
      ]),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Row(
            children: <Widget>[
              // 头像
              CircleAvatar(
                backgroundImage: storeList[index].logo != ''
                    ? NetworkImage(
                        storeList[index].logo,
                      )
                    : AssetImage(
                        'images/defaultLogo.png',
                      ),
                radius: 20,
              ),
              // 店名
              Container(
                margin: EdgeInsets.only(left: 8),
                child: Text(
                    "${storeList[index].brandName}(${storeList[index].shopName})"),
              ),
            ],
          ),
          // 单选框
          RoundCheckBox(
            value: storeList[index].checked,
            activeColor: ColorUtil.color("#FFC49226"),
            onChanged: (bool val) {
              setState(() {
                // 其他的不想选
                storeList.forEach((element) {
                  element.checked = false;
                });
                storeList[index].checked = !storeList[index].checked;
              });
            },
          )
        ],
      ),
    );
  }

  // 数据请求，加载门店列表
  void _loadData() {
    // 加载弹窗
    // showLoadingDialog(context);
    CommonDao.GetStoreList().then((StoreListModel model) => {
          // 关闭弹窗
          // Navigator.pop(context),
          // Future.delayed(Duration(seconds: 2), () {
            LoadingPop.hide(context),
          // }),
          if (model.status == 200)
            {
              setState(() {
                // 处理门店列表数据
                var list = model.data?.map((e) {
                  return e.storeInfo;
                });
                storeList = list.map((element) {
                  return Store(element.logoPic, element.brandName,
                      element.shopName, false, element.iD);
                }).toList();
                // 将门店列表存起来，方便以后使用
                context.read<StoreListProvider>().setStoreList(storeList);
              })
            }
        });
  }

// 确定登录哪个门店
  void _confirmStore(BuildContext context) {
    // SharedPreferences prefs = await SharedPreferences.getInstance();
    // 遍历是那个门店选中，将门店的StorId存起来
    storeList.forEach((element) {
      if (element.checked == true) {
        setStorage('Store-ID', element.storeId.toString());
        // 判断用户是否有注册商户的信息，是否通过审核,决定跳转到哪个页面
        _getStoreDetailById(element.storeId, context);
      }
    });
  }

// 获取门店详情数据
  void _getStoreDetailById(storeId, BuildContext context) {
    // 加载弹窗
    showLoadingDialog(context);
    CommonDao.GetStoreDetail(storeId).then((StoreDetailModel model) => {
          // 关闭弹窗
          Navigator.pop(context),
          if (model.status == 200)
            // 将商户信息存起来
            context
                .read<MerchantInfoProvider>()
                .setMerchantInfo(model.data.merchant),
          {
            if (model.data.status == '审核成功')
              {
                // 获取B端首页信息
                _getIndexData(context),
              }
            else if (model.data.status == '审核中')
              {}
            else if (model.data.status == '审核失败')
              {}
            else
              {
                // 第一次填写表单数据
                // 然后跳转商户信息登记
                Navigator.of(context).push(CustomRoute(MerChantInfoPage(), 4))
              }
          }
        });
  }

// 获取B端首页数据
  _getIndexData(BuildContext context) {
    CommonDao.GetIndexData().then((IndexDataModel model) => {
          if (model.status == 200)
            {
              // 存门店信息
              context
                  .read<StoreInfoProvider>()
                  .setStoreInfo(model.data.storeInfo),
              // 存登录者信息
              context
                  .read<ManagerInfoProvider>()
                  .setManagerInfo(model.data.managerInfo),
              // 存登录者的角色信息
              context.read<RoleInfoProvider>().setRoleInfo(model.data.roleInfo),
              // 跳转到我的门店
              Navigator.of(context).push(CustomRoute(MyStore(), 4)),
              LoadingPop.show(context)
            }
        });
  }
}

// 门店对象
class Store {
  String logo;
  String brandName;
  String shopName;
  bool checked;
  int storeId;
  // 构造方法
  Store(this.logo, this.brandName, this.shopName, this.checked, this.storeId);
}
